package com.sc.nft.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class IdCardAuditUtil {



    /**
     *  身份证,手机号,姓名三要素实名认证
     */
    public static String get(Map<String, String> params) throws IOException {
        String url = "https://slysjsys.market.alicloudapi.com/check";
        String appCode = "b1697e6429fb45418cb981e61b306504";
        url = url + buildRequestUrl(params);
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).build();
        Response response = client.newCall(request).execute();
        if(ObjectUtil.isEmpty(response)){
            return null;
        }
        return response.body().string();
    }

    public static String buildRequestUrl(Map<String, String> params) {
        StringBuilder url = new StringBuilder("?");
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            url.append(key).append("=").append(params.get(key)).append("&");
        }
        return url.toString().substring(0, url.length() - 1);
    }

    /**
     * 身份证二要素认证
     */
    public static JSONObject twoElementsOfIdCard(Map<String, String> bodys) throws IOException {
        String host = "https://zidv2.market.alicloudapi.com";
        String path = "/idcheck/Post";
        String method = "POST";
        String appcode = "644330f148bc48639d945f5bb4641538";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的body
            //{"error_code":0,"reason":"成功","result":{"realname":"刘**","idcard":"341226************","isok":true,"IdCardInfor":{"province":"安徽省","city":"阜阳市","district":"颍上县","area":"安徽省阜阳市颍上县","sex":"男","birthday":"1991-9-17"}},"sn":"083120414072665149440840973"}
            String string = EntityUtils.toString(response.getEntity());
            log.info("实名认证参数:{},请求结果:{}",bodys.toString(),string);
            return JSONObject.parseObject(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 身份证二要素实名认证
     */
    public static String postForm(Map<String, String> params) throws IOException {
        String url = "https://eid.shumaidata.com/eid/check";
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + "b1697e6429fb45418cb981e61b306504").post(body).build();
        Response response = client.newCall(request).execute();
        log.info("实名认证信息请求参数 姓名:{},身份证:{}", params.get("name"), params.get("idcard"));
        String result = response.body().string();
        log.info("实名认证信息返回结果:{}", result);
        return result;
    }


    /**
     * 人脸,身份证,姓名 三要素
     */

    public static String verifySelfieIdnumber(String idCard,String name,String img) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("id_number", idCard)
                .addFormDataPart("name", name)
                .addFormDataPart("url", img)
                .build();
        Request request = new Request.Builder()
                .url("https://cloudapi.deepfinch.com/face/v2/verify_selfie_idnumber")
                .method("POST", body)
                .addHeader("X-DF-API-ID", "05459f112e784c248e31e625e6baaf42")
                .addHeader("X-DF-API-SECRET", "1e67edef4a2c465791823ad050bad73f")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}
